package net.hky365.lowcode.framework.web.config;

import lombok.extern.slf4j.Slf4j;
import net.hky365.shop.framework.common.util.CommonUtils;
import net.hky365.shop.framework.swagger.config.Hky365SwaggerAutoConfiguration;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

import java.util.HashMap;

/**
 * low code 模块的 web 组件的 Configuration
 *
 * @author 芋道源码
 */
@Slf4j
@ComponentScan("net.hky365.lowcode")
@EnableConfigurationProperties(LowCodeWebConfiguration.DocsGroup.class)
public class LowCodeWebConfiguration {

    /**
     * 低代码, 管理功能
     */
    @Bean
    public GroupedOpenApi lowCodeGroupedOpenApi() {
        return Hky365SwaggerAutoConfiguration.buildGroupedOpenApi("low-code");
    }

    // @Bean
    public GroupedOpenApi lowCodeBusinessGroupedOpenApi() {
        String group = "yk";
        return GroupedOpenApi.builder()
                .group(group)
                .pathsToMatch(group)
                .addOperationCustomizer((operation, handlerMethod) -> operation
                        .addParametersItem(Hky365SwaggerAutoConfiguration.buildTenantHeaderParameter())
                        .addParametersItem(Hky365SwaggerAutoConfiguration.buildSecurityHeaderParameter()))
                .build();
    }


    // @Bean
    public GroupedOpenApi[] docsGroup(DocsGroup docsGroup) throws Exception {
        // Map<String, String> docsGroup = new HashMap<>(); magic-api.swagger.
        if (CommonUtils.isEmpty(docsGroup)) {
            log.info("Not any doc group need config. ");
            return new GroupedOpenApi[0];
        }

        return docsGroup.entrySet().stream().map(item -> {
            log.info("config {}: {}", item.getValue(), item.getKey());
            return GroupedOpenApi.builder()
                    .group(item.getValue())
                    .pathsToMatch(item.getValue())
                    .addOperationCustomizer((operation, handlerMethod) -> operation
                            .addParametersItem(Hky365SwaggerAutoConfiguration.buildTenantHeaderParameter())
                            .addParametersItem(Hky365SwaggerAutoConfiguration.buildSecurityHeaderParameter())).build();
        }).toArray(GroupedOpenApi[]::new);
    }

    @ConfigurationProperties("magic-api.swagger.docs-group")
    public static class DocsGroup extends HashMap<String, String> {

    }
}
